//
//  WebViewController.m
//  demo
//
//  Created by xinhualong on 2024/9/23.
//

#import "WebViewController.h"
#import <WebKit/WebKit.h>
#import "HomeRequest.h"
#import <StoreKit/StoreKit.h>

@interface WebViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (strong, nonatomic) WKWebView *webView;
@property (strong, nonatomic) UIActivityIndicatorView *activityindicatiorView;

@end

@implementation WebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    

    
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *contentController = [[WKUserContentController alloc] init];
    [contentController addScriptMessageHandler:self name:@"angrily"];
    [contentController addScriptMessageHandler:self name:@"demanded"];
    [contentController addScriptMessageHandler:self name:@"mad"];
    [contentController addScriptMessageHandler:self name:@"guess"];
    [contentController addScriptMessageHandler:self name:@"fellow"];
    config.userContentController = contentController;
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, SYS_TopHeight, SCREEN_WIDTH, SCREEN_HEIGHT-SYS_TopHeight) configuration:config];
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];
    
    self.navBgImageView.hidden = NO;
    [self.backButton addTarget:self action:@selector(clickBack) forControlEvents:UIControlEventTouchUpInside];
    
    NSURLRequest *requestUrl = [[NSURLRequest alloc] initWithURL: [NSURL URLWithString:self.url]];
    [self.webView loadRequest:requestUrl];
    self.webView.navigationDelegate = self;
    
    self.activityindicatiorView = [[UIActivityIndicatorView alloc] init];
    [self.view addSubview:self.activityindicatiorView];
    [self.activityindicatiorView startAnimating];
    [self.activityindicatiorView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
    }];
    
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
   
    [self.activityindicatiorView stopAnimating];
    self.activityindicatiorView.hidden = YES;
    self.ch_title = webView.title;
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *url = navigationAction.request.URL.absoluteString;
    
    if ([url containsString:@"mobikwik://"] || [url containsString:@"phonepe://"] || [url containsString:@"paytm://"] || [url containsString:@"paytmmp://"] || [url containsString:@"gpay://"] || [url containsString:@"upi://"]) {
      
        [UIApplication.sharedApplication openURL:[NSURL URLWithString:url] options:@{} completionHandler:^(BOOL success) {
           
            if (success) {
                decisionHandler(WKNavigationActionPolicyCancel);
            }else{
                decisionHandler(WKNavigationActionPolicyAllow);
            }
        }];
        
     
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
   
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    
    NSLog(@"call js method name: %@ ------params-----%@", message.name,message.body);
    if ([message.name isEqualToString:@"angrily"]) {
        
        [self.navigationController popViewControllerAnimated:YES];
        
    }else if ([message.name isEqualToString:@"demanded"]) {
        // back home
        [self.navigationController popToRootViewControllerAnimated:YES];
        [[NSNotificationCenter defaultCenter] postNotificationName:NotificationBackHomeKey object:@{@"index":@(0)}];
        
    }else if ([message.name isEqualToString:@"mad"]) {
     
        NSString *url = @"";
        if([message.body isKindOfClass:[NSString class]]){
            url = message.body;
        }else if ([message.body isKindOfClass:[NSArray class]] ){
            NSArray *array = message.body;
            url = array[0];
        }
        [self madParams:url];
        
    }else if ([message.name isEqualToString:@"guess"]) {
        
//        [self openAppStoreForRating];
        UIWindowScene *windowScene = self.view.window.windowScene;
        [SKStoreReviewController requestReviewInScene:windowScene];
        
    }else if ([message.name isEqualToString:@"fellow"]) {
       
        [HomeRequest requestUploadPointType:@"11" orderNo:@"" startTime:[BaseService getTimeStringSince1970] endTime:[BaseService getTimeStringSince1970] success:^(NSURLSessionDataTask *task, id response) {
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            
        }];
        
    }
}
- (void)madParams:(NSString *)url {

    NSLog(@"param11: %@", url);
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:url] options:@{} completionHandler:nil];

}

- (void)openAppStoreForRating {
    NSString *appID = @"YOUR_APP_ID";
    NSString *urlString = [NSString stringWithFormat:@"itms-apps://itunes.apple.com/app/id%@?action=write-review", appID];
    
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:urlString]]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString] options:@{} completionHandler:nil];
    }
}
- (void)clickBack{
    
    if (self.webView.canGoBack) {
       
        [self.webView goBack];
    } else {
        if(self.backRoot == 1){
            
            [self.navigationController popToRootViewControllerAnimated:YES];
        }else{
            
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
